// Simple command-line kernel monitor useful for
// controlling the kernel and exploring the system interactively.

#include <inc/stdio.h>
#include <inc/string.h>
#include <inc/memlayout.h>
#include <inc/assert.h>
#include <inc/x86.h>
#include <inc/mmu.h>

#include <kern/console.h>
#include <kern/monitor.h>
#include <kern/trap.h>
#include <kern/kdebug.h>

#define CMDBUF_SIZE	80	// enough for one VGA text line

struct Username_Password {
	const char * username;
	const char * password;
};

static struct Username_Password username_passwords[] = {
	{"root","stevengu" },
};

#define NUSER (sizeof(username_passwords)/sizeof(username_passwords[0]))


struct Command {
	const char *name;
	const char *desc;
	// return -1 to force monitor to exit
	int (*func)(int argc, char** argv, struct Trapframe* tf);
};

static struct Command commands[] = {
	{ "help", "Display this list of commands", mon_help },
	{ "kerninfo", "Display information about the kernel", mon_kerninfo },
	{ "backtrace", "Display backtrace of function", mon_backtrace },
//	{ "singlestep", "Single step through the program", mon_singlestep },
};
#define NCOMMANDS (sizeof(commands)/sizeof(commands[0]))

unsigned read_eip();

/***** Implementations of basic kernel monitor commands *****/

int
mon_help(int argc, char **argv, struct Trapframe *tf)
{
	int i;

	for (i = 0; i < NCOMMANDS; i++)
		cprintf("%s - %s\n", commands[i].name, commands[i].desc);
	return 0;
}

int
mon_kerninfo(int argc, char **argv, struct Trapframe *tf)
{
	extern char _start[], etext[], edata[], end[];

	cprintf("Special kernel symbols:\n");
	cprintf("  _start %08x (virt)  %08x (phys)\n", _start, _start - KERNBASE);
	cprintf("  etext  %08x (virt)  %08x (phys)\n", etext, etext - KERNBASE);
	cprintf("  edata  %08x (virt)  %08x (phys)\n", edata, edata - KERNBASE);
	cprintf("  end    %08x (virt)  %08x (phys)\n", end, end - KERNBASE);
	cprintf("Kernel executable memory footprint: %dKB\n",(end-_start+1023)/1024);
	return 0;
}

int
mon_backtrace(int argc, char **argv, struct Trapframe *tf)
{
	
	int* ebp = (int*)read_ebp();
	int* eip = (int*)read_eip();
	int* arg[5]={0};
	while(ebp!= 0)
	//the loop end 
	//if it returns to its initial state 0 
	//and the trace of function has been to the origin
	{
		struct Eipdebuginfo info; 
		int i;
		for(i=0;i<5;i++)
			arg[i] = (int*)*((ebp+i+2));
	        debuginfo_eip((uintptr_t)eip,&info);
		char fun_name[30];
		strlcpy(fun_name,info.eip_fn_name,info.eip_fn_namelen+1);	
		cprintf("%s:%0d:%s:%d\n",info.eip_file,info.eip_line,fun_name,info.eip_fn_narg);
		cprintf("ebp %08x eip %08x args %08x %08x %08x %08x %08x\n",
				ebp,eip,arg[0],arg[1],arg[2],arg[3],arg[4]);
		ebp = (int*)*(ebp);//the content of the ebp point to is the saved previous ebp
		eip = (int*)*(ebp+1);  
	}
	return 0;
}
/*
int
mon_singlestep(int argc, char **argv, struct Trapframe *tf)
{
	asm volatile("pushfl");
	asm volatile("popl %eax");
	asm volatile("orl $0x100,%eax");
	asm volatile("pushl %eax");
	asm volatile("popfl");
	return 1;
}
*/

/***** Kernel monitor command interpreter *****/

#define WHITESPACE "\t\r\n "
#define MAXARGS 16

static int
runcmd(char *buf, struct Trapframe *tf)
{
	int argc;
	char *argv[MAXARGS];
	int i;

	// Parse the command buffer into whitespace-separated arguments
	argc = 0;
	argv[argc] = 0;
	while (1) {
		// gobble whitespace
		while (*buf && strchr(WHITESPACE, *buf))
			*buf++ = 0;
		if (*buf == 0)
			break;

		// save and scan past next arg
		if (argc == MAXARGS-1) {
			cprintf("Too many arguments (max %d)\n", MAXARGS);
			return 0;
		}
		argv[argc++] = buf;
		while (*buf && !strchr(WHITESPACE, *buf))
			buf++;
	}
	argv[argc] = 0;

	// Lookup and invoke the command
	if (argc == 0)
		return 0;
	for (i = 0; i < NCOMMANDS; i++) {
		if (strcmp(argv[0], commands[i].name) == 0)
			return commands[i].func(argc, argv, tf);
	}
	cprintf("Unknown command '%s'\n", argv[0]);
	return 0;
}

void
monitor(struct Trapframe *tf)
{
	char *buf;
	int r;

	cprintf("Welcome to the JOS kernel monitor!\n");
	cprintf("Type 'help' for a list of commands.\n");

	if (tf != NULL)
		print_trapframe(tf);

	while (1) {
		buf = readline("K> ");
		if (buf != NULL)
		{
			if ((r = runcmd(buf, tf)) < 0)
				break;
		}
			

	}
}

// return EIP of caller.
// does not work if inlined.
// putting at the end of the file seems to prevent inlining.
unsigned
read_eip()
{
	uint32_t callerpc;
	__asm __volatile("movl 4(%%ebp), %0" : "=r" (callerpc));
	return callerpc;
}

int 
login()
{
	char *username,*password;
	int i;
	username = readline("username:");
	for(i = 0; i < NUSER; i++)
	{
		if(!strcmp(username, username_passwords[i].username))
		{
			password = secretreadline("password:");
			if(!strcmp(password, username_passwords[i].password))
			{
				cprintf("\n");
				return 0;
			}
			else 
			{
				cprintf("\nwrong password!\n");
				return -1;
			}
		}
	}
	cprintf("No such username\n");
	return -1;


}
